package Servers

import (
	"DBModel"
	"PBMessage"
	"SGNet"
	"misc/mgo/bson"
	proto "misc/protobuf/proto"
	log "misc/seelog"
)

func (hallServer *HallServer) Init_Account() {
	hallServer.AddNetHandler(PBMessage.PBID_CS_RegAccount, hallServer.CS_RegAccount_Handler)
	hallServer.AddNetHandler(PBMessage.PBID_CS_Login, hallServer.CS_Login_Handler)
}

func (hallServer *HallServer) CS_RegAccount_Handler(message *SGNet.Message) {
	CSRegAccount := &PBMessage.CS_RegAccount{}
	proto.Unmarshal(message.Data, CSRegAccount)
	SCRegAccount := &PBMessage.SC_RegAccount{}
	if DBModel.AccountModel_CheckByAccount(CSRegAccount.GetAccount()) {
		SCRegAccount.Type = proto.Int32(1)
	} else {
		SCRegAccount.Type = proto.Int32(0)
		DBModel.NewAccount(CSRegAccount.GetAccount(), CSRegAccount.GetNickName(), CSRegAccount.GetPwd())
	}
	message.Sess.SendPacket(PBMessage.PBID_SC_RegAccount, SCRegAccount)
}

func (hallServer *HallServer) CS_Login_Handler(message *SGNet.Message) {
	CSLogin := &PBMessage.CS_Login{}
	proto.Unmarshal(message.Data, CSLogin)

	query := DBModel.Db.C("sp_Account").Find(bson.M{"account": CSLogin.GetAccount(), "pwd": CSLogin.GetPwd()})
	var queryData DBModel.AccountModel
	err := query.One(&queryData)
	if err != nil {
		log.Info(err)
	}
	SCLogin := &PBMessage.SC_Login{}
	if num, _ := query.Count(); num > 0 && hallServer.GetPlayerByAccount(queryData.Account) == nil {
		SCLogin.Type = proto.Int32(0)
		SCLogin.NickName = proto.String(queryData.NickName)
		log.Info(CSLogin.GetIsRobot())
		hallPlayer := NewHallPlayer(&queryData, message.Sess, nil)
		hallServer.AddPlayer(hallPlayer)

		SCLogin.UserId = proto.Int64(hallPlayer.UserId)
		message.Sess.UserData = hallPlayer
		log.Info(CSLogin.GetAccount() + "登录成功")
	} else {
		log.Info(CSLogin.GetAccount() + "登录失败")
		SCLogin.Type = proto.Int32(1)
	}
	message.Sess.SendPacket(PBMessage.PBID_SC_Login, SCLogin)
}
